package com.guodexian.xiaomi.controller;

import com.alibaba.fastjson.JSON;
import com.guodexian.xiaomi.entity.User;
import com.guodexian.xiaomi.service.UserService;
import com.guodexian.xiaomi.service.impl.UserServiceImpl;
import com.guodexian.xiaomi.util.HttpResponseUtil;
import com.guodexian.xiaomi.util.RedisUtil;
import com.guodexian.xiaomi.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 类说明：  <br>
 *
 * @author 南阳德刚<br>
 * 2024-12-30 14:56<br>
 * @since 1.0 <br>
 * 培养IT高薪技术人才的摇篮---北京学佳澳。<br>
 * 点击<a href="http://www.xuejiaao.com/images/qrcode.jpg">学佳澳教育</a>关注公共号,有惊喜(⊙o⊙)<br>
 */
@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        String verkey = req.getParameter("verkey");
        // 2 输出
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String redisCaptcha = RedisUtil.getJedis().get(verkey);
        if (!captcha.equalsIgnoreCase(redisCaptcha)) {
            //删除redis，否则会造成无效数据越来越多
            RedisUtil.getJedis().del(verkey);
            HttpResponseUtil.response(resp, ResultVO.fail("验证码不一致"));
            return;
        }

        //ResultVO user = userService.findUserByNameAndPassword(username, password);
        //out.print(JSON.toJSONString(user));

        User user = userService.findUserByNameAndPassword(username, password);
        if (user == null) {
            HttpResponseUtil.response(resp, ResultVO.fail("用户不存在"));
        } else if(!user.getPassword().equals(password)) {
            HttpResponseUtil.response(resp, ResultVO.fail("密码错误"));
        } else {
            HttpResponseUtil.response(resp, ResultVO.success(user));
//            out.print(JSON.toJSONString(ResultVO.success(user)));
        }

        out.flush();
        out.close();
    }

}